﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.KPIPage
{
    public partial class HosKPIItem : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBaseData();
                BindData();
            }
            PublicMethod.GetApprovalButton("HosKPIItem.aspx", Toolbar2, Grid1);
        }

        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {
            DataTable tableItemType = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,DICT_NAME FROM SYSTEM_DICT WHERE PARENT_ID = (SELECT TOP 1 
                                                                                   REC_ID FROM SYSTEM_DICT WHERE PARENT_ID=0 AND DICT_NAME ='医院评分类')").Tables[0];
            ddlSearchKPI_ITEM_TYPE.DataTextField = "DICT_NAME";
            ddlSearchKPI_ITEM_TYPE.DataValueField = "REC_ID";
            ddlSearchKPI_ITEM_TYPE.DataSource = tableItemType;
            ddlSearchKPI_ITEM_TYPE.DataBind();
            FineUIPro.ListItem searchItem = new FineUIPro.ListItem();
            searchItem.Value = "0";
            searchItem.Text = "全部";
            ddlSearchKPI_ITEM_TYPE.Items.Insert(0, searchItem);
            
            ddlFormKPI_ITEM_TYPE.DataTextField = "DICT_NAME";
            ddlFormKPI_ITEM_TYPE.DataValueField = "REC_ID";
            ddlFormKPI_ITEM_TYPE.DataSource = tableItemType;
            ddlFormKPI_ITEM_TYPE.DataBind();


            DataTable tableDeptType = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,DICT_NAME FROM SYSTEM_DICT WHERE PARENT_ID = (SELECT TOP 1 
                                                                                   REC_ID FROM SYSTEM_DICT WHERE PARENT_ID=0 AND DICT_NAME ='部门类别')").Tables[0];
            ddlFormKPI_ITEM_DEPT_TYPE.DataTextField = "DICT_NAME";
            ddlFormKPI_ITEM_DEPT_TYPE.DataValueField = "REC_ID";
            ddlFormKPI_ITEM_DEPT_TYPE.DataSource = tableDeptType;
            ddlFormKPI_ITEM_DEPT_TYPE.DataBind();
            
        }

        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindData()
        {
            StringBuilder sqlWhere = new StringBuilder();
            String mainDataSql = @"SELECT A.REC_ID,A.KPI_ITEM_NAME,A.KPI_ITEM_EXPLAIN,A.KPI_ITEM_SCORE,A.KPI_ITEM_REMARK,A.KPI_ITEM_STATUS,A.KPI_ITEM_TYPE,
                                   CASE WHEN A.KPI_ITEM_STATUS=1 THEN '启用' WHEN A.KPI_ITEM_STATUS=0 THEN '停用' END AS KPI_ITEM_STATUS_NAME,KPI_ITEM_DEPT_TYPE,
                                   (SELECT DICT_NAME FROM SYSTEM_DICT WHERE REC_ID = A.KPI_ITEM_TYPE) AS KPI_ITEM_TYPE_NAME,
                                    (SELECT DICT_NAME FROM SYSTEM_DICT WHERE REC_ID = A.KPI_ITEM_DEPT_TYPE) AS KPI_ITEM_DEPT_TYPE_NAME
                                    FROM HOS_KPI_ITEM AS A WHERE 1=1 {0}";
            if (tbxNameSerach.Text.Trim() != "")
            {
                sqlWhere.Append(" AND A.KPI_ITEM_NAME LIKE '%" + tbxNameSerach.Text.Trim() + "%'");
            }
            if (ddlSearchKPI_ITEM_TYPE.SelectedValue != "0" && ddlSearchKPI_ITEM_TYPE.SelectedValue != null)
            {
                sqlWhere.Append(" AND A.KPI_ITEM_TYPE = "+ ddlSearchKPI_ITEM_TYPE.SelectedValue);
            }
            mainDataSql = string.Format(mainDataSql, sqlWhere.ToString());
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];
            Grid1.DataSource = mainDataTable;
            Grid1.DataBind();
        }

        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_KPI_ITEM WHERE REC_ID="+ rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = Grid1.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            book = PublicMethod.NPOIExcel(Grid1);
            MemoryStream ms = new MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("指标列表", System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            Response.End();
            book = null;
            ms.Close();
            ms.Dispose();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                if (tbxFormKPI_ITEM_NAME.Text.Trim() != "")
                {
                    keyValuePairs.Add("KPI_ITEM_NAME", tbxFormKPI_ITEM_NAME.Text.Trim());
                }
                else
                {
                    ShowNotify("指标名称不能为空!");
                    return;
                }
                if (tbxFormKPI_ITEM_SCORE.Text.Trim() != "")
                {
                    keyValuePairs.Add("KPI_ITEM_SCORE", tbxFormKPI_ITEM_SCORE.Text.Trim());
                }
                else
                {
                    ShowNotify("指标分值不能为空!");
                    return;
                }
                if (tbxFormKPI_ITEM_EXPLAIN.Text.Trim() != "")
                {
                    keyValuePairs.Add("KPI_ITEM_EXPLAIN", tbxFormKPI_ITEM_EXPLAIN.Text.Trim());
                }
                if (tbxFormKPI_ITEM_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("KPI_ITEM_REMARK", tbxFormKPI_ITEM_REMARK.Text.Trim());
                }
                if (ddlFormKPI_ITEM_TYPE.SelectedValue != "" && ddlFormKPI_ITEM_TYPE.SelectedValue != null)
                {
                    keyValuePairs.Add("KPI_ITEM_TYPE", ddlFormKPI_ITEM_TYPE.SelectedValue);
                }
                if (ddlFormKPI_ITEM_DEPT_TYPE.SelectedValue != "" && ddlFormKPI_ITEM_DEPT_TYPE.SelectedValue != null)
                {
                    keyValuePairs.Add("KPI_ITEM_DEPT_TYPE", ddlFormKPI_ITEM_DEPT_TYPE.SelectedValue);
                }
                if (ddlFormKPI_ITEM_STATUS.SelectedValue != "" && ddlFormKPI_ITEM_STATUS.SelectedValue != null)
                {
                    keyValuePairs.Add("KPI_ITEM_STATUS", ddlFormKPI_ITEM_STATUS.SelectedValue);
                }
                String strRowID = hfFormID.Text;
                if (String.IsNullOrEmpty(strRowID))
                {
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_KPI_ITEM WHERE 1=2", "Add", keyValuePairs);

                    ShowNotify("保存成功!");
                }
                else
                {
                    keyValuePairs.Add("REC_ID", strRowID);
                    keyValuePairs.Add("UPDATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("UPDATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_KPI_ITEM WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindData();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", Grid1.ClientID, "1") + Window1.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
    }
}